package com.likai.jarscms.realm;

import com.likai.jarscms.pojo.Manager;
import com.likai.jarscms.service.IManagerService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

/**
 * Created by likai on 2018/10/14.
 */
public class MyRealm extends AuthorizingRealm {

    @Autowired
    @Qualifier("managerService")
    private IManagerService managerService ;

    /**
     * 为当前登陆用户授予角色和权限
     * @param principals
     * @return
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        return null;
    }

    /**
     * 验证当前登陆的用户
     * @param token
     * @return
     * @throws AuthenticationException
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户名
        String username = (String) token.getPrincipal() ;
        Manager manager = managerService.findByUserName(username) ;

        if(manager != null) {
            //存入session
            SecurityUtils.getSubject().getSession().setAttribute("currentUser",manager);
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(manager.getUsername(), manager.getPassword(), "shiro");
            return authcInfo ;
        } else {
            return null;
        }

    }
}
